Masthead

Converting International Dates

There are a large number of different date fromats. Fortunately, the international date format is taking over. This format specifies that dates should be formatted as "YYYY-MM-DDTHH:MM:SS". Where the "T" divides the string into date and time and the other letters stand for Year, Month, Day, Hour, Minute, and Second, respectively. This date is great for international data exchange but it is unfamiliar to most folks. To use the date on a map, we areally need a freindlier version.

Note: When we refer to a "date" in techincal terms, we are really refering to both the date and time. Some folks will use "Time Stamp" to refer to a date/time combination.

Download a file from the USGS Earthquake Data Center or use this one. Then, write the function below to extract the various elements of the date. Then, you'll need to complete the function to return a nice looking date string.

TheFile=open("C:/Temp/4.5_week.csv","r") # open the file for reading (thus the "r")

NumLines=0
TheHeader=TheFile.readline() # read the header line from the file

TheLine=TheFile.readline() # read the next line in the file
while ((TheLine!="") and (NumLines<100)): # while the line is not blank, go through this loop

	TheElements=TheLine.split(",") # split up the columns of the line
	
	TheDateTimeString=TheElements[0] # get the datetime string
	print(TheDateTimeString) # print the string for debugging

	TheLine=TheFile.readline() # read the next line in the file
	NumLines+=1 # add one to count the number of lines read

TheFile.close()

print("Read "+format(NumLines)+" lines from the file")

Note that the date time string has a "T" to divide the date and time. Use the "split()" function to break up this string.

	TheDateTimeElements=TheDateTimeString.split("T") # split the date and time into separate strings
	
	TheDateString=TheDateTimeElements[0] # get the date string
	TheTimeString=TheDateTimeElements[1] # get the time string
	

Next, we can use the dash character to split up the date and obtain strings for each of the date elements.

	TheDateElements=TheDateString.split("-") # break up the date elements
	
	TheYearString=TheDateElements[0]
	TheMonthString=TheDateElements[1]
	TheDayString=TheDateElements[2]

Now we can reformat our date to be in whatever format we desire.

Additional Resources

Python Documentation: String functions

Python Documentation: Defining Functions

 

© Copyright 2018 HSU - All rights reserved.